package com.hjx.movie.common.utils.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>Title:</p>
 * <p>Description:</p>
 *
 * @author hjx
 * @date 2021/1/8 - 18:33
 */
public class DataTreeUtil {

    public static <T extends DataTreeNode<T>> List<T> buildTree2(List<T> paramList,Long rootNodeId){
//        long start = System.currentTimeMillis();
        List<T> root = new ArrayList<>();
        int index = -1;
        for (int i=0;i<paramList.size();i++){
            T node = paramList.get(i);
            if (node.getNodeId().equals(rootNodeId)){
                root.add(node);
                index = i;
                break;
            }
        }
        if (index!=-1){
            paramList.remove(index);
        }
        toTreeChildren(root,paramList);
//        long timeMillis = System.currentTimeMillis()-start;
//        System.out.println("buildTree2使用的时间:"+timeMillis/1000+" ms");
        return root;
    }

    public static <T extends DataTreeNode<T>> void toTreeChildren(List<T> root,List<T> paramList){
        for (T entry:root){
            if (!entry.getIsLeaf()){
                if (entry.getChildren()==null){
                    entry.setChildren(new ArrayList<>());
                }
                ArrayList<T> removeList = new ArrayList<>();
                for (T node : paramList) {
                    if (node.getParentId().equals(entry.getNodeId())) {
                        entry.getChildren().add(node);
                        removeList.add(node);
                    }
                }
                for (T removeNode:removeList){
                    paramList.remove(removeNode);
                }
                toTreeChildren(entry.getChildren(),paramList);
            }
        }

    }


    public static <T extends DataTreeNode<T>> List<T> buildTree(List<T> paramList,Long rootNodeId){
        long start = System.currentTimeMillis();
        List<T> returnList = new ArrayList<>();
        for (T node:paramList){
            if (node.getNodeId().equals(rootNodeId)){
                returnList.add(node);
            }
        }
        for (T entry:paramList){
            toTreeChildren(returnList,entry);
        }
        long timeMillis = System.currentTimeMillis()-start;
        System.out.println(timeMillis/1000);
        return returnList;
    }

    public static <T extends DataTreeNode<T>> void toTreeChildren(List<T> returnList, T entry) {
        for (T node:returnList){
            //判断当前节点是不是entry的父节点
            if (entry.getParentId().equals(node.getNodeId())){
                if (node.getChildren()==null){
                    node.setChildren(new ArrayList<>());
                }
                node.getChildren().add(entry);
            }
            //如果当前节点不是 就找当前节点的子节点
            if (node.getChildren()!=null){
                toTreeChildren(node.getChildren(),entry);
            }

        }
    }

}
